package com.base.db.mysql

import com.base.config.BaseConfig
import com.base.db.redis.autoCache_list
import com.base.db.redis.autoCache_map
import com.base.db.redis.autoCache_string
import com.base.model.api.*
import com.base.utils.ULID
import com.base.utils.toYuan
import com.google.gson.Gson

//检查用户是否存在_登录名
fun MySQLService.app_checkUserIsExistByUserName(loginname: String): Boolean {
    if (loginname.isBlank()) return false
    return mapper.app_checkUserIsExistByUserName(loginname) > 0
}

//检查用户是否存在_UID+密码
fun MySQLService.app_checkUserIsExistByUidPassword(uid: String, password: String): Boolean {
    if (uid.isBlank() || password.isBlank()) return false
    return mapper.app_checkUserIsExistByUidPassword(uid, password) > 0
}

//创建用户_用户名密码方式
fun MySQLService.app_addUserByAccountPassword(loginname: String, password: String): Boolean {
    if (loginname.isBlank() || password.isBlank()) return false
    val yimUser = ULID().nextULID()
    val yimToken = yimService.registerToken(yimUser) ?: return false
    val _uid = ""
    if (mapper.app_addUserByAccountPassword(loginname, password, yimUser, yimToken, _uid) <= 0) return false
    return mapper.app_addUserExt(_uid) > 0
}

//创建用户_验证码方式
fun MySQLService.app_addUserByPhone(phone: String): Boolean {
    if (phone.isBlank()) return false
    val yimUser = ULID().nextULID()
    val yimToken = yimService.registerToken(yimUser) ?: return false
    val _uid = ""
    if (mapper.app_addUserByPhone(phone, yimUser, yimToken, _uid) <= 0) return false
    return mapper.app_addUserExt(_uid) > 0
}

//创建用户_三方登录方式
fun MySQLService.app_addUserByThird(platform: String, thirdID: String): Boolean {
    if (platform.isBlank() || thirdID.isBlank()) return false
    val yimUser = ULID().nextULID()
    val yimToken = yimService.registerToken(yimUser) ?: return false
    val _uid = ""
    if (mapper.app_addUserByThird(platform, thirdID, yimUser, yimToken, _uid) <= 0) return false
    return mapper.app_addUserExt(_uid) > 0
}

//修改用户_用户名密码方式
fun MySQLService.app_updateUserByAccount(uid: String, password: String): Boolean {
    if (uid.isBlank() || password.isBlank()) return false
    return mapper.app_updateUserByAccount(uid, password) > 0
}

//修改用户_验证码方式
fun MySQLService.app_updateUserByPhone(uid: String, phone: String): Boolean {
    if (uid.isBlank() || phone.isBlank()) return false
    return mapper.app_updateUserByPhone(uid, phone) > 0
}

//修改用户_三方登录方式
fun MySQLService.app_updateUserByThird(uid: String, platform: String, thirdID: String): Boolean {
    if (uid.isBlank() || platform.isBlank() || thirdID.isBlank()) return false
    return mapper.app_updateUserByThird(uid, platform, thirdID) > 0
}

//获取用户_用户名密码方式
fun MySQLService.app_getUserByAccount(loginname: String, password: String): String? {
    if (loginname.isBlank() || password.isBlank()) return null
    return mapper.app_getUserByAccount(loginname, password)?.firstOrNull()?.get("id")?.toString()
}

//获取用户_验证码方式
fun MySQLService.app_getUserByPhone(phone: String): String? {
    if (phone.isBlank()) return null
    val uid = mapper.app_getUserByPhone(phone)?.firstOrNull()?.get("id")?.toString()
    if (uid == null) {
        //创建用户
        if (!app_addUserByPhone(phone)) return null
        return app_getUserByPhone(phone)
    }
    return uid
}

//获取用户_三方登录方式
fun MySQLService.app_getUserByThird(platform: String, thirdID: String): String? {
    if (platform.isBlank() || thirdID.isBlank()) return null
    val uid = mapper.app_getUserByThird(platform, thirdID)?.firstOrNull()?.get("id")?.toString()
    if (uid == null) {
        //创建用户
        if (!app_addUserByThird(platform, thirdID)) return null
        return app_getUserByThird(platform, thirdID)
    }
    return uid
}

//获取账号绑定状态
fun MySQLService.app_getUserBindStatusByID(uid: String): BindStatusModel? {
    if (uid.isBlank()) return null
    return mapper.app_getUserBindStatusByID(uid)?.firstOrNull()
}

//获取用户登录信息
fun MySQLService.app_getUserInfoByUID(uid: String): UserModel_App? {
    if (uid.isBlank()) return null
    return mapper.app_getUserInfoByUID(uid)?.firstOrNull()
}

//查询app主页banners_big
fun MySQLService.app_getHome_banners_big(): List<ShouYeTJModel.ShouYeTJModel_Banner>? {
    return redisService.autoCache_list("app_getHome_banners_big") {
        mapper.app_getHome_banners(1)
    }
}

//查询app主页banners_left
fun MySQLService.app_getHome_banners_left(): List<ShouYeTJModel.ShouYeTJModel_Banner>? {
    return redisService.autoCache_list("app_getHome_banners_left") {
        mapper.app_getHome_banners(2)
    }
}

//查询app主页banners_right
fun MySQLService.app_getHome_banners_right(): List<ShouYeTJModel.ShouYeTJModel_Banner>? {
    return redisService.autoCache_list("app_getHome_banners_right") {
        mapper.app_getHome_banners(3)
    }
}

//查询app主页banners_func
fun MySQLService.app_getHome_banners_func(): List<ShouYeTJModel.ShouYeTJModel_Banner>? {
    return redisService.autoCache_list("app_getHome_banners_func") {
        mapper.app_getHome_banners(4)
    }
}

//查询app主页productItems
fun MySQLService.app_getHome_productItems(pageSize: Int): List<ProductListModel.ProductListSubModel>? {
    if (pageSize <= 0) return null
    return redisService.autoCache_list("app_getHome_productItems") {
        mapper.app_getHome_productItems(pageSize)
    }
}

//查询主页分类
fun MySQLService.app_getCategory(): List<ShouYeFLModel.ShouYeFLModel_Group.ShouYeFLModel_Item>? {
    return redisService.autoCache_list("app_getCategory") {
        mapper.app_getCategory()
    }
}

//随机查询一组短视频
fun MySQLService.app_getVideos(pageSize: Int): List<VideoModel>? {
    if (pageSize < 5) return null
    return redisService.autoCache_list("app_getVideos") {
        mapper.app_getVideos(pageSize)
    }
}

//插入视频
fun MySQLService.app_addVideo(uid: String, video: String): Boolean {
    if (uid.isEmpty() || video.isEmpty()) return false
    return mapper.app_addVideo(uid, video) > 0
}

//更新用户头像
fun MySQLService.app_updateUserAvatar(uid: String, avatar: String): Boolean {
    if (uid.isEmpty() || avatar.isEmpty()) return false
    return mapper.app_updateUserAvatar(uid, avatar) > 0
}

//更新用户昵称
fun MySQLService.app_updateUserName(uid: String, name: String): Boolean {
    if (uid.isEmpty() || name.isEmpty()) return false
    return mapper.app_updateUserName(uid, name) > 0
}

//通过SPUID查询SPU详情
fun MySQLService.app_getSPUDetailById(id: String): Map<String, Any?>? {
    if (id.isEmpty()) return null
    return redisService.autoCache_map("app_getSPUDetailById_$id") {
        val result = mapper.app_getSPUDetailById(id)?.firstOrNull() ?: return@autoCache_map null
        result["img_banner"] = Gson().fromJson(result["img_banner"].toString(), List::class.java).map { "${BaseConfig.ossBaseURL}$it" }
        result["img_detail"] = Gson().fromJson(result["img_detail"].toString(), List::class.java).map { "${BaseConfig.ossBaseURL}$it" }
        return@autoCache_map result
    }
}

//通过SPUID查询所有SKU
fun MySQLService.app_getSKUsBySPUId(id: String): List<Map<String, Any?>>? {
    if (id.isEmpty()) return null
    return redisService.autoCache_list("app_getSKUsBySPUId_$id") {
        mapper.app_getSKUsBySPUId(id)
    }
}

//获取客服
fun MySQLService.app_getService(): Map<String, Any?>? {
    return redisService.autoCache_map("app_getService") {
        mapper.app_getService()?.firstOrNull()
    }
}

//更新用户扩展
fun MySQLService.app_updateUserExtById(uid: String, carts: List<String>? = null, collections: List<String>? = null): Boolean {
    if (uid.isEmpty()) return false
    return mapper.app_updateUserExtById(
            uid,
            if (carts == null) null else Gson().toJson(carts),
            if (collections == null) null else Gson().toJson(collections),
    ) > 0
}

//获取用户扩展
fun MySQLService.app_getUserExtById(uid: String): UserModel_App_Ext? {
    if (uid.isEmpty()) return null
    val result = mapper.app_getUserExtById(uid)?.firstOrNull() ?: return null
    val userModelExt = UserModel_App_Ext()
    userModelExt.id = result["id"]?.toString()
    userModelExt.collections = Gson().fromJson(result["collections"]?.toString(), ArrayList::class.java) as ArrayList<String>
    userModelExt.carts = Gson().fromJson(result["carts"]?.toString(), ArrayList::class.java) as ArrayList<String>
    return userModelExt
}

//获取购物车列表
fun MySQLService.app_getCartBySku(skus: List<String>): List<CartListModel.CartMainModel>? {
    if (skus.isEmpty()) return listOf()
    return mapper.app_getCartBySku(skus)
}

//获取评论数量
fun MySQLService.app_getReplyCountBySku(spu: String): Int? {
    if (spu.isEmpty()) return null
    return redisService.autoCache_string("app_getReplyCountBySku_$spu") {
        mapper.app_getReplyCountBySku(spu)?.toString()
    }?.toInt()
}

//分页评论数据
fun MySQLService.app_getReplysBySku(spu: String, page: Int, pageSize: Int): List<ReplyModel>? {
    if (spu.isEmpty() || page <= 0 || pageSize <= 0) return null
    return mapper.app_getReplysBySku(spu, page, pageSize)
}

//查询SPU列表
fun MySQLService.app_getSPUs(content: String?, page: Int, pageSize: Int, orderBy: String, type: String?): List<ProductListModel.ProductListSubModel>? {
    if (page <= 0 || pageSize <= 0 || orderBy.isEmpty()) return null
    return mapper.app_getSPUs(content, page, pageSize, orderBy, type)?.map {
        it.money1 = it.money1.toYuan()
        it.money2 = "-${it.money2.toYuan()}"
        it
    }?.toList()
}